package cn.gs.serializable.entity;

// @author gs
import cn.gs.serializable.old.SerializableTool;
import cn.gs.util.stream.TokenReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapEntity implements IEntity {

    private Map<IEntity, IEntity> map = new HashMap<IEntity, IEntity>(0);

    public MapEntity() {
    }
    
    public MapEntity(Map<IEntity, IEntity> entities) {
        this.map.putAll(entities);
    }

    @Override
    public void write(EntityController ctrl, Writer w) throws IOException {
        boolean b = false;
        w.write("{");
        for (Map.Entry<IEntity, IEntity> i : getMap().entrySet()) {
            if (b) {
                w.write(",");
            } else {
                b = true;
            }
            i.getKey().write(ctrl, w);
            w.write(":");
            i.getValue().write(ctrl, w);
        }
        w.write("}");
    }

    @Override
    public boolean read(EntityController ctrl, TokenReader reader) throws IOException {
        String c = reader.get();
        if (!"{".equals(c.trim())) {
            reader.back();
            return false;
        }
        setMap(new HashMap<IEntity, IEntity>());
        do {
            IEntity k = ctrl.read(reader);
            if (k != null) {
                c = reader.get();
                if (!":".equals(c.trim())) {
                    reader.back();
                    return false;
                }
                IEntity v = ctrl.read(reader);
                if (v != null) {
                    getMap().put(k, v);
                } else {
                    return false;
                }
                c = reader.get();
                if (!",".equals(c.trim())) {
                    reader.back();
                    break;
                }
            } else {
                break;
            }
        } while (true);
        c = reader.get();
        if (!"}".equals(c.trim())) {
            reader.back();
            return false;
        }
        return true;
    }

    @Override
    public String toString(String prefix) {
        StringWriter w = new StringWriter();
        w.write("{\n");
        for (Map.Entry<IEntity, IEntity> i : getMap().entrySet()) {
            String s = i.getKey().toString(prefix + " ");
            w.write(s);
            w.write(":");
            s = i.getValue().toString("");
            w.write(s);
            w.write("\n");
        }
        w.write(prefix);
        w.write("}");
        return w.toString();
    }

    @Override
    public String toString() {
        return toString("");
    }

    public Map<IEntity, IEntity> getMap() {
        return map;
    }

    public void setMap(Map<IEntity, IEntity> map) {
        this.map = map;
    }
}
